<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\View;

class Home extends BaseController
{
    /**
     * 首页
     */
    public function index()
    {
        $userId = get_user_id();
        
        if (is_logged_in()) {
            // 登录用户：获取用户的个性化数据
            $settings = Db::name('user_settings')->where('user_id', $userId)->find();
            $quickLinks = Db::name('quick_links')->where('user_id', $userId)->order('sort_order', 'asc')->select();
            $tools = Db::name('tools')->where('user_id', $userId)->order('sort_order', 'asc')->select();
            $bookmarks = Db::name('bookmarks')->where('user_id', $userId)->order('sort_order', 'asc')->select();
        } else {
            // 未登录用户：提供默认数据
            $settings = [
                'theme' => 'light',
                'layout' => 'grid',
                'search_engine' => 'bing',
                'time_format' => '24h'
            ];
            
            // 默认快捷导航
            $quickLinks = [
                ['title' => '百度', 'url' => 'https://www.baidu.com', 'icon' => '🔍'],
                ['title' => '谷歌', 'url' => 'https://www.google.com', 'icon' => '🌐'],
                ['title' => 'GitHub', 'url' => 'https://github.com', 'icon' => '💻'],
                ['title' => '知乎', 'url' => 'https://www.zhihu.com', 'icon' => '📚']
            ];
            
            // 默认常用工具
            $tools = [
                ['title' => '计算器', 'url' => 'https://www.calculator.net', 'icon' => '🧮'],
                ['title' => '翻译', 'url' => 'https://fanyi.baidu.com', 'icon' => '🔤'],
                ['title' => '天气', 'url' => 'https://www.weather.com', 'icon' => '🌤️'],
                ['title' => '地图', 'url' => 'https://map.baidu.com', 'icon' => '🗺️']
            ];
            
            // 默认收藏夹
            $bookmarks = [
                ['title' => '新闻', 'url' => 'https://news.sina.com.cn', 'icon' => '📰'],
                ['title' => '视频', 'url' => 'https://www.bilibili.com', 'icon' => '🎬'],
                ['title' => '音乐', 'url' => 'https://music.163.com', 'icon' => '🎵'],
                ['title' => '购物', 'url' => 'https://www.taobao.com', 'icon' => '🛒']
            ];
        }

        View::assign([
            'settings' => $settings ?: [],
            'quickLinks' => $quickLinks ?: [],
            'tools' => $tools ?: [],
            'bookmarks' => $bookmarks ?: []
        ]);

        return View::fetch('index');
    }

    /**
     * 保存个性化设置
     */
    public function saveSettings()
    {
        if (!is_logged_in()) {
            return error('请先登录');
        }

        $userId = get_user_id();
        $data = $this->request->post();

        // 验证数据
        $settings = [
            'theme' => $data['theme'] ?? 'light',
            'layout' => $data['layout'] ?? 'grid',
            'search_engine' => $data['search_engine'] ?? 'bing',
            'time_format' => $data['time_format'] ?? '24h',
            'updated_at' => date('Y-m-d H:i:s')
        ];

        $existing = Db::name('user_settings')->where('user_id', $userId)->find();
        
        if ($existing) {
            Db::name('user_settings')->where('user_id', $userId)->update($settings);
        } else {
            $settings['user_id'] = $userId;
            $settings['created_at'] = date('Y-m-d H:i:s');
            Db::name('user_settings')->insert($settings);
        }

        return success(null, '设置保存成功');
    }

    /**
     * 添加快捷导航
     */
    public function addQuickLink()
    {
        if (!is_logged_in()) {
            return error('请先登录');
        }

        $userId = get_user_id();
        $title = $this->request->post('title');
        $url = $this->request->post('url');
        $icon = $this->request->post('icon', '🔗');

        if (empty($title) || empty($url)) {
            return error('标题和URL不能为空');
        }

        // 检查是否已存在
        $existing = Db::name('quick_links')
            ->where('user_id', $userId)
            ->where('url', $url)
            ->find();

        if ($existing) {
            return error('该链接已存在');
        }

        // 获取最大排序值
        $maxOrder = Db::name('quick_links')
            ->where('user_id', $userId)
            ->max('sort_order') ?? 0;

        $linkData = [
            'user_id' => $userId,
            'title' => $title,
            'url' => $url,
            'icon' => $icon,
            'sort_order' => $maxOrder + 1,
            'created_at' => date('Y-m-d H:i:s')
        ];

        $result = Db::name('quick_links')->insert($linkData);

        if ($result) {
            return success($linkData, '添加快捷导航成功');
        }

        return error('添加失败');
    }

    /**
     * 删除快捷导航
     */
    public function deleteQuickLink()
    {
        if (!is_logged_in()) {
            return error('请先登录');
        }

        $userId = get_user_id();
        $linkId = $this->request->post('id');

        $result = Db::name('quick_links')
            ->where('id', $linkId)
            ->where('user_id', $userId)
            ->delete();

        if ($result) {
            return success(null, '删除成功');
        }

        return error('删除失败');
    }

    /**
     * 添加常用工具
     */
    public function addTool()
    {
        if (!is_logged_in()) {
            return error('请先登录');
        }

        $userId = get_user_id();
        $title = $this->request->post('title');
        $url = $this->request->post('url');
        $icon = $this->request->post('icon', '🔧');

        if (empty($title) || empty($url)) {
            return error('标题和URL不能为空');
        }

        // 检查是否已存在
        $existing = Db::name('tools')
            ->where('user_id', $userId)
            ->where('url', $url)
            ->find();

        if ($existing) {
            return error('该工具已存在');
        }

        // 获取最大排序值
        $maxOrder = Db::name('tools')
            ->where('user_id', $userId)
            ->max('sort_order') ?? 0;

        $toolData = [
            'user_id' => $userId,
            'title' => $title,
            'url' => $url,
            'icon' => $icon,
            'sort_order' => $maxOrder + 1,
            'created_at' => date('Y-m-d H:i:s')
        ];

        $result = Db::name('tools')->insert($toolData);

        if ($result) {
            return success($toolData, '添加工具成功');
        }

        return error('添加失败');
    }

    /**
     * 添加收藏
     */
    public function addBookmark()
    {
        if (!is_logged_in()) {
            return error('请先登录');
        }

        $userId = get_user_id();
        $title = $this->request->post('title');
        $url = $this->request->post('url');
        $icon = $this->request->post('icon', '📌');

        if (empty($title) || empty($url)) {
            return error('标题和URL不能为空');
        }

        // 检查是否已存在
        $existing = Db::name('bookmarks')
            ->where('user_id', $userId)
            ->where('url', $url)
            ->find();

        if ($existing) {
            return error('该收藏已存在');
        }

        // 获取最大排序值
        $maxOrder = Db::name('bookmarks')
            ->where('user_id', $userId)
            ->max('sort_order') ?? 0;

        $bookmarkData = [
            'user_id' => $userId,
            'title' => $title,
            'url' => $url,
            'icon' => $icon,
            'sort_order' => $maxOrder + 1,
            'created_at' => date('Y-m-d H:i:s')
        ];

        $result = Db::name('bookmarks')->insert($bookmarkData);

        if ($result) {
            return success($bookmarkData, '添加收藏成功');
        }

        return error('添加失败');
    }

    /**
     * 获取用户数据（用于同步）
     */
    public function getUserData()
    {
        if (!is_logged_in()) {
            return error('请先登录');
        }

        $userId = get_user_id();
        
        $data = [
            'settings' => Db::name('user_settings')->where('user_id', $userId)->find() ?: [],
            'quickLinks' => Db::name('quick_links')->where('user_id', $userId)->order('sort_order', 'asc')->select()->toArray(),
            'tools' => Db::name('tools')->where('user_id', $userId)->order('sort_order', 'asc')->select()->toArray(),
            'bookmarks' => Db::name('bookmarks')->where('user_id', $userId)->order('sort_order', 'asc')->select()->toArray()
        ];

        return success($data);
    }
}